package com.baizhi.service.impl;

import com.baizhi.dao.ClazzDao;
import com.baizhi.dao.StudentDao;
import com.baizhi.entity.Student;
import com.baizhi.service.StudentService;
import com.baizhi.util.MybatisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    @Override
    public PageInfo<Student> selectByPage(int pageNo, int pageSize) {
        SqlSession session = null;
        PageHelper.startPage(pageNo,pageSize);
        List<Student> stuList = null;
        try {
            session = MybatisUtil.getSqlSession();
            StudentDao sd = session.getMapper(StudentDao.class);
            stuList = sd.selectAll();
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
        return new PageInfo<>(stuList);
    }

    @Override
    public Student selectOne(int id) {
        SqlSession session = null;
        Student stu = null;
        try {
            session = MybatisUtil.getSqlSession();
            StudentDao sd = session.getMapper(StudentDao.class);
            stu = sd.selectOne(id);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
        return stu;
    }

    @Override
    public void insert(Student stu) {
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            StudentDao sd = session.getMapper(StudentDao.class);
            sd.insert(stu);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
    }

    @Override
    public void delete(int id) {
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            StudentDao sd = session.getMapper(StudentDao.class);
            sd.delete(id);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
    }

    @Override
    public void update(Student stu) {
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            StudentDao sd = session.getMapper(StudentDao.class);
            sd.update(stu);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
    }
}
